package cn.jbolt.admin.demotable;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.core.poi.excel.JBoltExcel;
import cn.jbolt.core.poi.excel.JBoltExcelHeader;
import cn.jbolt.core.poi.excel.JBoltExcelSheet;
import cn.jbolt.core.poi.excel.JBoltExcelUtil;
import com.jfinal.plugin.activerecord.Page;

import java.io.File;
import java.util.*;

import cn.jbolt.extend.systemlog.ProjectSystemLogTargetType;
import cn.jbolt.core.service.base.JBoltBaseService;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import cn.jbolt.core.base.JBoltMsg;
import cn.jbolt.core.db.sql.Sql;
import cn.jbolt.admin.demotable.model.DemoTable;

/**
 * demo测试表
 *
 * @ClassName: DemoTableService
 * @author: 山东小木
 * @date: 2023-10-27 15:45
 */
public class DemoTableService extends JBoltBaseService<DemoTable> {
    private final DemoTable dao = new DemoTable().dao();

    @Override
    protected DemoTable dao() {
        return dao;
    }

    @Override
    protected int systemLogTargetType() {
        return ProjectSystemLogTargetType.NONE.getValue();
    }

    /**
     * 后台管理数据查询
     *
     * @param pageNumber 第几页
     * @param pageSize   每页几条数据
     * @param keywords   关键词
     * @param sortColumn 排序列名
     * @param sortType   排序方式 asc desc
     * @param sex        性别
     * @param enable     是否启用
     * @param startTime  开始时间
     * @param type       类型
     * @param state      状态
     * @param createTime 创建时间
     * @return
     */
    public Page<DemoTable> getAdminDatas(int pageNumber, int pageSize, String keywords, String sortColumn, String sortType, Integer sex, Boolean enable, Date startTime, Integer type, Integer state, Date createTime) {
        //创建sql对象
        Sql sql = selectSql().page(pageNumber, pageSize);
        //sql条件处理
        sql.eq("sex", sex);
        sql.eqBooleanToChar("enable", enable);
        sql.eq("start_time", startTime);
        sql.eq("type", type);
        sql.eq("state", state);
        sql.eq("create_time", createTime);
        //关键词模糊查询
        sql.likeMulti(keywords, "name", "sn", "title", "hobbys", "phone", "email", "user_name", "brief_info", "content");
        //排序
        sql.orderBy(sortColumn, sortType);
        return paginate(sql);
    }

    /**
     * 后台管理数据查询
     *
     * @param keywords   关键词
     * @param sortColumn 排序列名
     * @param sortType   排序方式 asc desc
     * @param sex        性别
     * @param enable     是否启用
     * @param startTime  开始时间
     * @param type       类型
     * @param state      状态
     * @param createTime 创建时间
     * @return
     */
    public List<DemoTable> getAllAdminDatas(String keywords, String sortColumn, String sortType, Integer sex, Boolean enable, Date startTime, Integer type, Integer state, Date createTime) {
        //创建sql对象
        Sql sql = selectSql();
        //sql条件处理
        sql.eq("sex", sex);
        sql.eqBooleanToChar("enable", enable);
        sql.eq("start_time", startTime);
        sql.eq("type", type);
        sql.eq("state", state);
        sql.eq("create_time", createTime);
        //关键词模糊查询
        sql.likeMulti(keywords, "name", "sn", "title", "hobbys", "phone", "email", "user_name", "brief_info", "content");
        //排序
        sql.orderBy(sortColumn, sortType);
        return find(sql);
    }

    /**
     * 保存
     *
     * @param demoTable
     * @return
     */
    public Ret save(DemoTable demoTable) {
        if (demoTable == null || isOk(demoTable.getId())) {
            return fail(JBoltMsg.PARAM_ERROR);
        }
        if (existsSn(demoTable.getSn())) {
            return fail(JBoltMsg.DATA_SAME_SN_EXIST);
        }
        boolean success = demoTable.save();
        if (success) {
            //添加日志
            //addSaveSystemLog(demoTable.getId(), JBoltUserKit.getUserId(), demoTable.getName());
        }
        return ret(success);
    }

    /**
     * 更新
     *
     * @param demoTable
     * @return
     */
    public Ret update(DemoTable demoTable) {
        if (demoTable == null || notOk(demoTable.getId())) {
            return fail(JBoltMsg.PARAM_ERROR);
        }
        //更新时需要判断数据存在
        DemoTable dbDemoTable = findById(demoTable.getId());
        if (dbDemoTable == null) {
            return fail(JBoltMsg.DATA_NOT_EXIST);
        }
        if (existsSn(demoTable.getSn(), demoTable.getId())) {
            return fail(JBoltMsg.DATA_SAME_SN_EXIST);
        }
        boolean success = demoTable.update();
        if (success) {
            //添加日志
            //addUpdateSystemLog(demoTable.getId(), JBoltUserKit.getUserId(), demoTable.getName());
        }
        return ret(success);
    }

    /**
     * 检测是否可以删除
     *
     * @param demoTable 要删除的model
     * @param kv        携带额外参数一般用不上
     * @return
     */
    @Override
    public String checkCanDelete(DemoTable demoTable, Kv kv) {
        //如果检测被用了 返回信息 则阻止删除 如果返回null 则正常执行删除
        return checkInUse(demoTable, kv);
    }

    /**
     * 删除数据后执行的回调
     *
     * @param demoTable 要删除的model
     * @param kv        携带额外参数一般用不上
     * @return
     */
    @Override
    protected String afterDelete(DemoTable demoTable, Kv kv) {
        //addDeleteSystemLog(demoTable.getId(), JBoltUserKit.getUserId(),demoTable.getName());
        return null;
    }

    /**
     * 检测是否可以删除
     *
     * @param demoTable model
     * @param kv        携带额外参数一般用不上
     * @return
     */
    @Override
    public String checkInUse(DemoTable demoTable, Kv kv) {
        //这里用来覆盖 检测是否被其它表引用
        return null;
    }

    /**
     * 检测是否可以toggle操作指定列
     *
     * @param demoTable 要toggle的model
     * @param column    操作的哪一列
     * @param kv        携带额外参数一般用不上
     * @return
     */
    @Override
    public String checkCanToggle(DemoTable demoTable, String column, Kv kv) {
        //没有问题就返回null  有问题就返回提示string 字符串
        return null;
    }

    /**
     * toggle操作执行后的回调处理
     */
    @Override
    protected String afterToggleBoolean(DemoTable demoTable, String column, Kv kv) {
        //addUpdateSystemLog(demoTable.getId(), JBoltUserKit.getUserId(), demoTable.getName(),"的字段["+column+"]值:"+demoTable.get(column));
        /**
         switch(column){
         case "enable":
         break;
         }
         */
        return null;
    }


	/**
	 * 使用excel批量导入
	 * @param file
	 * @return
	 */
    public Ret importExcel(File file) {
        JBoltExcel excel = JBoltExcel.from(file).setSheets(
                JBoltExcelSheet.create("Demo").setDataStartRow(2)
                        .setHeaders(1,
                                JBoltExcelHeader.create(DemoTable.SN, "编号", 20).col(1),
                                JBoltExcelHeader.create(DemoTable.NAME, "姓名", 20).col(2),
                                JBoltExcelHeader.create(DemoTable.USER_NAME, "用户名", 20).col(3),
                                JBoltExcelHeader.create(DemoTable.PHONE, "手机号", 30).col(4),
                                JBoltExcelHeader.create(DemoTable.EMAIL, "邮箱", 20).col(5),
                                JBoltExcelHeader.create(DemoTable.SEX, "性别", 10).col(6),
                                JBoltExcelHeader.create(DemoTable.AGE, "年龄", 10).col(7),
                                JBoltExcelHeader.create(DemoTable.SCORE, "积分", 10).col(8)
                        ).setDataChangeHandler((data, index) -> {
                            String sn = data.getStr(DemoTable.SN);
                            if (notOk(sn)) {
                                throw new RuntimeException("excel中第[" + (index+1) + "]行数据的[编号]列为空");
                            }
                            String name = data.getStr(DemoTable.NAME);
                            if (notOk(name)) {
                                throw new RuntimeException("excel中第[" + (index+1) + "]行数据的[姓名]列为空");
                            }
                            String userName = data.getStr(DemoTable.USER_NAME);
                            if (notOk(userName)) {
                                throw new RuntimeException("excel中第[" + (index+1) + "]行数据的[用户名]列为空");
                            }
                            String phone = data.getStr(DemoTable.PHONE);
                            if (notOk(phone)) {
                                throw new RuntimeException("excel中第[" + (index+1) + "]行数据的[手机号]列为空");
                            }
                            String age = data.getStr(DemoTable.AGE);
                            if (notOk(age)) {
                                throw new RuntimeException("excel中第[" + (index+1) + "]行数据的[年龄]列为空");
                            }
                            String sex = data.getStr(DemoTable.SEX);
                            if (Objects.equals(sex, "男")) {
                                data.change(DemoTable.SEX, 1);
                            } else if (Objects.equals(sex, "女")) {
                                data.change(DemoTable.SEX, 2);
                            } else {
                                data.change(DemoTable.SEX, 0);
                            }
                        })
        );
        StringBuilder sb = new StringBuilder();
        List<DemoTable> demoTables = JBoltExcelUtil.readModels(excel, DemoTable.class, sb);
        if (sb.length() > 0) {
            return fail(sb.toString());
        }
        if (notOk(demoTables)) {
            return fail("excel中无有效数据");
        }
        HashSet<String> snSet = new HashSet<>();
        for (int i = 0; i < demoTables.size(); i++) {
            DemoTable item = demoTables.get(i);
            if (snSet.add(item.getSn()) == false || existsSn(item.getSn())) {
				//同表格中或者数据库中，如果编号重复，就提示错误
                return fail(StrUtil.format("第{}行数据填入的编号[{}]已存在，不可重复添加", i+2, item.getSn()));
            }
            //做其他处理...
            item.setTitle("");
            item.setType(1);
            item.setEnable(true);
            item.setState(1);
        }
        batchSave(demoTables);
        return SUCCESS;
    }
}
